from aiogram import Bot, Dispatcher
from aiogram.filters import Text
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import any_state
from aiogram.types import Message, ReplyKeyboardRemove
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import sessionmaker

from app.bot.keyboards.reply import user_keyboard
from app.bot.states.states import WhitePage
from app.bot.utils.logger import log
from app.bot.utils.scheduler import jobs
from app.database.functions.stats import update_stats, update_user_stats
from app.database.functions.whitepages import add_whitepage


async def generate_docs(message: Message, state: FSMContext) -> None:
    """
    Генератор вайтов
    """

    await message.answer(
        "Сколько вайтов сгенерировать?", reply_markup=ReplyKeyboardRemove()
    )
    await message.answer("Отправьте /cancel, чтобы вернуться в главное меню")
    await state.set_state(WhitePage.waiting_amount)


async def select_amount(
    message: Message,
    bot: Bot,
    session: AsyncSession,
    session_factory: sessionmaker,
    scheduler: AsyncIOScheduler,
    state: FSMContext,
) -> None:
    if not message.text.isdigit():
        await message.answer("Введите число цифрой")
        await state.set_state(WhitePage.waiting_amount)
        return

    for i in range(0, int(message.text)):
        await add_whitepage(session, message.from_user.id)

    scheduler.add_job(
        jobs.check_whites,
        "interval",
        name="Whitepages",
        seconds=30,
        args=(bot, session_factory, scheduler, message.from_user.id),
    )
    log.info(
        f"Добавлена задача по генерации {message.text} вайта(ов) от пользователя {message.from_user.id}"
    )
    await update_stats(session, whitepages=int(message.text))
    await update_user_stats(
        session, message.from_user.id, whitepages_generated=int(message.text)
    )

    await message.answer("Задача принята в работу", reply_markup=user_keyboard())
    await state.clear()


def register_white_generator_handlers(dp: Dispatcher):
    dp.message.register(
        generate_docs, Text(text="📰 Генератор вайтов", ignore_case=True), any_state
    )
    dp.message.register(select_amount, WhitePage.waiting_amount)
